<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="企业名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入企业名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="企业信用代码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入企业信用代码" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="企业类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择企业类型" clearable size="small">
          <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in statusOptions1" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-show="roleId != 6" type="primary" plain icon="" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-if="false">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :height="tableHeight" :data="enterpriseList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" show-overflow-tooltip />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="企业名称" align="center" prop="name" />
      <el-table-column label="社会信用代码" align="center" prop="code" />
      <el-table-column label="企业类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="企业联系人" align="center" prop="contacts" />
      <el-table-column label="联系电话" align="center" prop="mobile" />
      <!-- <el-table-column label="资质文件" align="center" prop="ennum">
        <template slot-scope="scope">
          
          <el-link type="primary" :href="'/basics/certification?id=' + scope.row.id">{{ scope.row.ennum }}</el-link>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
           <span>{{ statusOptions2[scope.row.status]  }}</span>
          <!-- <dict-tag :value="scope.row.status" /> -->
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-if="roleId != 6" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
           >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
           >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="企业名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="社会信用代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入社会信用代码" />
        </el-form-item>
        <el-form-item label="企业类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择企业类型">
            <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入企业联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions1" :key="dict.dictValue" :label="dict.dictValue*1">{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from '@/utils'
import { listEnterprise2, getEnterprise, logicDelEnterprise, addEnterprise1, updateEnterprise, exportEnterprise } from "@/api/enterprise/enterprise";
import Cookies from "js-cookie";

export default {
  name: "Enterprise",
  data() {
    var validateStatus = (rule, value, callback) => {
      if (value === undefined || value === null || value === 0) {
        callback(new Error('请选择状态'));
      } else {
        callback();
      }
    }
    var validatePhone = (rule, value, callback) => {
      if (value === undefined || value === null || value === 0) {
        callback(new Error('联系电话不能为空'));
      }
      let regex = /^1[3-9]\d{9}$/
      if(!regex.test(value)){
        callback(new Error('请输入有效的手机号'));
      }
      callback();
    }
    return {
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      enterpriseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 企业类型字典
      typeOptions: [],
      // 状态 1=开业，2=停业字典
      statusOptions: [],
      statusOptions1: [],
      statusOptions2:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        type: null,
        status: null,
      },
      // 表单参数
      form: {
       
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "社会信用代码不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "企业类型不能为空", trigger: "blur" }
        ],
        contacts: [
          { required: true, message: "企业联系人不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
          // { required: true, validator: validatePhone, trigger: "blur" }
        ],
        //    status: [
        //   { required: true, message: "不能为空", trigger: "change" }
        // ],
        status: [
          { required: true, validator: validateStatus, trigger: "change" }
        ],
      },
      roleId:null,
      roles:[],
      enterpriseId:null,
    };
  },
  created() {
    //当前用户的信息
    let userInfo =JSON.parse( Cookies.get("userinfo" ));
    this.roles = userInfo.roles
    this.roleId = userInfo.roleId
    this.enterpriseId = userInfo.enterpriseId
    console.log("tangddd")
    console.log(this.roles)
    console.log(this.roleId)

    this.getList();
    this.calHeight()
    this.getDicts("gc_enterprise_type").then(response => {
      this.typeOptions = response.data;
    });

  },
  mounted() {
    this.getDicts("gc_enterprise_status").then(response => {
      this.statusOptions1 = response.data;

      let data = response.data
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel
      });
      this.statusOptions2 = new_arr;

    });

    console.log('statusOptions1:', this.statusOptions1);
    console.log('form.status:', this.form.status);
  },
  watch: {
    'showSearch': 'calHeight'
  },
  methods: {
   
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.appcontainer.getBoundingClientRect();
        let height = this.$refs.queryForm.$el.offsetHeight;
        this.tableHeight = rect.height - height - 120;
      })
    },
    /** 查询企业信息列表 */
    getList() {
      this.loading = true;
      for(let i=0; i <this.roles.length;i++){
        if(this.roles[i].roleId == 6 || this.roles[i].roleId == 9){
          this.queryParams.id = this.enterpriseId
          break;
        }
      }


      listEnterprise2(this.queryParams).then(response => {
        this.enterpriseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        type: null,
        contacts: null,
        mobile: null,
        status: 0,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch = true;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEnterprise(id).then(response => {
        this.form = response.data;
        console.log('this.form',this.form.status)
        // 确保status转换为数字类型
        this.form.status = Number(response.data.status);
        this.open = true;
        this.title = "修改企业信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.code !== this.form.mobile) {
            if (this.form.id != null) {
              updateEnterprise(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
               
              });
            } else {
              addEnterprise1(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
               
              });
            }
            return
          } else {
           
            this.$message.error(`信用代码和手机号不可重复`)
          }
        } else {
   
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return logicDelEnterprise(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企业信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportEnterprise(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => { });
    }
  }
};
</script>
